import 'package:syria_sports/presentation/admin_home_tabs/players_tab/widgets/player_grid_item_view.dart';

import '../../../core/app_export.dart';
import '../../../core/network/internet_cubit.dart';
import '../../../dialogs/soon_dialog.dart';
import '../../../widgets/app_bar/appbar_subtitle.dart';
import '../../../widgets/app_bar/custom_app_bar.dart';
import '../../../widgets/app_bar/outline_icon_button.dart';
import '../../../widgets/custom_search_view.dart';
import '../../../widgets/screen_state_widget.dart';
import '../../players/add_player_page/bloc/add_player_page_screen.dart';
import 'widgets/player_list_item_view.dart';
import 'bloc/players_tab_cubit.dart';
import 'package:flutter/material.dart';

class PlayersTabScreen extends StatelessWidget {
  const PlayersTabScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;

    return BlocConsumer<PlayersTabCubit, PlayersTabState>(
      listener: (context, state) {
        // TODO: implement listener
      },
      builder: (context, state) {
        var cubit = PlayersTabCubit.get(context);

        return Scaffold(
          appBar: _buildAppBar(context: context, cubit: cubit),
          body: Container(
            height: height,
            width: width,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(ImageConstant.imgBackground),
                fit: BoxFit.cover,
              ),
            ),
            child: Column(
              children: [
                if (cubit.searchFlag)
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: CustomSearchView(
                      controller: cubit.searchBox,
                      hintText: 'ابحث عن اسم او رقم اللاعب',
                      //textDirection:
                      onChanged: (value) {
                        cubit.onSearch(value);
                      },
                      onClear: () {
                        cubit.onSearch('');
                      },
                    ),
                  ),
                Expanded(
                  child: ScreenStateWidget(
                    isDone: state is PlayersTabDone,
                    isError: state is PlayersTabError,
                    isLoading: state is PlayersTabLoading,
                    onRefresh: () {
                      cubit.add(PlayerTabInitialEvent());
                    },
                    onDone: (height*0.6 > width)
                        ? ListView.builder(
                            itemCount: cubit.users.length,
                            itemBuilder: (context, index) {
                              return PlayerListItemView(
                                user: cubit.users[index],
                                index: index,
                                playersTabCubit: cubit,
                                onSelected: (value,user){
                                  cubit.add(ChangeSelectedItem(value: value,user: user));
                                },
                              );
                            })
                        : GridView.builder(
                            gridDelegate:
                                const SliverGridDelegateWithMaxCrossAxisExtent(
                              maxCrossAxisExtent: 130,
                              mainAxisExtent: 180,
                            ),
                            itemCount: cubit.users.length,
                            itemBuilder: (context, index) {
                              return PlayerGridItemView(
                                user: cubit.users[index],
                                index: index,
                                playersTabCubit: cubit,
                                onSelected: (value,user){
                                  cubit.add(ChangeSelectedItem(value: value,user: user));
                                },
                              );
                            }),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  PreferredSizeWidget _buildAppBar(
      {required BuildContext context, required PlayersTabCubit cubit}) {
    return CustomAppBar(
      actions: [
        BlocBuilder<InternetCubit, InternetState>(
          builder: (context, state) {
            if (state == InternetState.disconnected) {
              return Padding(
                padding: const EdgeInsets.all(8.0),
                child: Image.asset(ImageConstant.icOffline),
              );
            } else if (PrefUtils.isGymAdmin()) {
              return OutlineIconButton(
                icon: Icons.add,
                margin: const EdgeInsets.all(8),
                padding: const EdgeInsets.all(2),
                onTapped: () async {
                  showPlayerDialog(context);
                },
              );
            }
            return const SizedBox();
          },
        )
      ],
      leading: Stack(
        children: [
          if (cubit.searchBox.text.isNotEmpty)
            const Padding(
              padding: EdgeInsets.all(8.0),
              child: Align(
                alignment: Alignment.bottomLeft,
                child: CircleAvatar(
                  radius: 6,
                  backgroundColor: Colors.green,
                ),
              ),
            ),
          Center(
            child: OutlineIconButton(
              icon: cubit.searchFlag ? Icons.search_off : Icons.search,
              margin: const EdgeInsets.all(8),
              padding: const EdgeInsets.all(2),
              onTapped: () async {
                cubit.onSearchTap();
              },
            ),
          ),
        ],
      ),
      title: AppbarSubtitle(text: 'اللاعبين'),
    );
  }

  void showPlayerDialog(BuildContext context1) {
    showDialog(
      context: context1,
      builder: (BuildContext context) {
        return AlertDialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15.0),
          ),
          title: const Text('إضافة لاعب'),
          content: const Text('اختر طريقة الإضافة:'),
          actions: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                ElevatedButton(
                  onPressed: () async {
                    Navigator.of(context).pop();
                    await Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => AddPlayerPageScreen(
                                  playersTabCubit:
                                      PlayersTabCubit.get(context1),
                                ))).then((value) {});
                  },
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.all(16),
                    backgroundColor: Colors.orangeAccent,
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text('إضافة لاعب جديد',
                        style: theme.textTheme.titleMedium),
                  ),
                ),
                const SizedBox(height: 10),
                ElevatedButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    // Action for adding player from platform
                    print('Adding player from platform');
                    showDialog(
                        barrierDismissible: true,
                        context: NavigatorService.navigatorKey.currentState!.overlay!.context,
                        builder: (BuildContext context) {
                          return const SoonDialog();
                        });
                  },
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.all(16),
                    backgroundColor: Colors.deepOrange,
                  ),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      'إضافة لاعب من المنصة',
                      style: theme.textTheme.titleMedium,
                    ),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );
  }
}
